#! /usr/bin/env python
#coding:utf-8

from __future__ import with_statement
import re
import os
import sys
from optparse import OptionParser
import itertools

def fetch_ret(commend):
    with os.popen(commend) as f:
        return f.read()
    #return os.popen(commend).read()

def diff(src, N, M):
    if M != -1:
        cmd =  "svn diff -r %s:%s %s" % (N, M, src)
    else:
        cmd = "svn diff -r %s %s" % (N, src)
    
    for i in fetch_ret(cmd).splitlines():
        ilen = len(i)
        if ilen < 3 and ilen > 0 and i[0] == "+":
            yield 1
        elif ilen > 3 and i[0] == "+" and i[0:3] != "+++":
            yield 1

#{'notedit': 3336, 'yuest': 3045, 'mzhou': 2319, 'aisk': 5926, 'changjiang': 20, 'jyf': 33456, 'luc': 8631, 'harry': 34345, 'philip': 92071, 'chika': 5385, 'soddy': 11393}
def blame(src):
    cmd = "svn list -R %s" % src
    spt = re.compile("[\s\W]+")
    dc = {}
    def author_gener():
        for f in fetch_ret(cmd).splitlines():
            if os.path.isfile(f):
                for i in fetch_ret("svn blame %s" % f).splitlines():
                    yield spt.split(i)[2]

    for key, items in itertools.groupby(author_gener()):
        dc[key] = dc.get(key, 0) + len(list(items))

    return dc
    

def main(*args, **kw):
    src = args[0]
    N = kw.get("n", None)
    M = kw.get("m", -1)
    action = kw.get("t", "diff")
    assert N != None

    if action == "diff":
        print sum(diff(src, N, M))
    elif action == "blame":
        print blame(src)


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option('-n','--basenumber',
            dest='n',
            type='int',
            default=-1,
            help='number of base reversion')
    parser.add_option('-m','--wcnumber',
            dest='m',
            type='int',
            default=-1,
            help='number of workcopy reversion')
    parser.add_option('-t','--action',
            dest='t',
            type='string',
            default="diff",
            help='statistics svn information type [diff, blame]')
    options, args = parser.parse_args()
    
    if options.n == -1 or len(args) < 1:
        print "Usage: statistics.py -n 100 ."
    else:
        main(*args, **dict([(k, getattr(options, k)) for k in dir(options)]))
